package com.itheima.service.db.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.domain.db.Users;
import com.itheima.mapper.AnalysisByDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.util.ComputeUtil;
import com.itheima.util.DateFormatUtil;
import com.itheima.vo.AnalysisSummaryVo;
import com.itheima.vo.UsersVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.swing.plaf.ComponentUI;
import java.awt.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@DubboService
public class AnalysisByDayServiceImpl implements AnalysisByDayService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    @Override
    public void logToAnalysisByDay() {
        // 1.准备基础数据
        // 1-1 今天 2021-12-07
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();
        // 1-2 昨天 2021-12-06
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();

        // 2.查询log
        // 2-1 今日注册
        Integer numRegistered = logMapper.findByTypeAndLogTime("0102", today);
        // 2-2 今日活跃
        Integer numActive = logMapper.findByLogTime(today);
        // 2-3 今日登录
        Integer numLogin = logMapper.findByTypeAndLogTime("0101", today);
        // 2-4 次日留存
        Integer numRetention1d = logMapper.findNumRetention1d(today, yesterday);

        // 3.同步新增、更新
        QueryWrapper<AnalysisByDay> qw = new QueryWrapper<>();
        qw.eq("record_date", today);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(qw);
        if (analysisByDay == null) { // 新增
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumRetention1d(numRetention1d);
            analysisByDayMapper.insert(analysisByDay);//  使用insert方法
        }else{ // 更新
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumRetention1d(numRetention1d);
            analysisByDayMapper.updateById(analysisByDay); // 使用update方法
        }
    }

    // 展示统计数据
    @Override
    public AnalysisSummaryVo findAnalysisSummaryVo() {
        // 1.准备基础数据
        // 1-1 今天
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();
        // 1-2 昨天
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();
        // 1-3 前7天
        String weekDay = DateUtil.offsetDay(new Date(), -6).toDateStr();
        // 1-4 前30天
        String monthDay = DateUtil.offsetDay(new Date(), -29).toDateStr();
        // 1-5 今日分析
        AnalysisByDay todayAnalysisByDay = analysisByDayMapper.findByRecordDate(today);
        // 1-6 昨天分析
        AnalysisByDay yesterdayAnalysisByDay = analysisByDayMapper.findByRecordDate(yesterday);

        // 2.凑齐9份数据
        // 2-1 累计用户数
        Long cumulativeUsers = analysisByDayMapper.findCumulativeUsers();
        // 2-2 过去30天活跃用户数
        Long activePassMonth = analysisByDayMapper.findActivePassCondition(monthDay, today);
        // 2-3 过去7天活跃用户
        Long activePassWeek = analysisByDayMapper.findActivePassCondition(weekDay, today);
        // 2-4 今日新增用户数量
        Integer newUsersToday = todayAnalysisByDay.getNumRegistered();
        // 2-5 日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal newUsersTodayRate = ComputeUtil.computeRate(newUsersToday, yesterdayAnalysisByDay.getNumRegistered());
        // 2-6 今日登录次数
        Integer loginTimesToday = todayAnalysisByDay.getNumLogin();
        // 2-7 日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal loginTimesTodayRate = ComputeUtil.computeRate(loginTimesToday, yesterdayAnalysisByDay.getNumLogin());
        // 2-8 今日活跃用户数量
        Integer activeUsersToday = todayAnalysisByDay.getNumActive();
        // 2-9 今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal activeUsersTodayRate = ComputeUtil.computeRate(activeUsersToday, yesterdayAnalysisByDay.getNumActive());

        // 3.封装并返回vo
        AnalysisSummaryVo vo = new AnalysisSummaryVo();
        vo.setCumulativeUsers(cumulativeUsers);
        vo.setActivePassMonth(activePassMonth);
        vo.setActivePassWeek(activePassWeek);
        vo.setNewUsersToday(newUsersToday.longValue());
        vo.setNewUsersTodayRate(newUsersTodayRate);
        vo.setLoginTimesToday(loginTimesToday.longValue());
        vo.setLoginTimesTodayRate(loginTimesTodayRate);
        vo.setActiveUsersToday(activeUsersToday.longValue());
        vo.setActiveUsersTodayRate(activeUsersTodayRate);

        return vo;
    }

    //展示新增数据统计图
    @Override
    public UsersVo findUsersVo(String type,String startTime, String endTime) {

        ArrayList<Users> thisYears = new ArrayList<>();
        ArrayList<Users> lastYears = new ArrayList<>();

        //String startTimeStr = null;
        String startTimeStr = DateUtil.formatDate(new Date(Long.valueOf(startTime)));
        String endTimeStr = DateUtil.formatDate(new Date(Long.valueOf(endTime)));

        int i = 0;
        Integer amount;
      while (!StrUtil.equals(startTimeStr, endTimeStr)) {
          startTimeStr = DateUtil.offsetDay(new Date(Long.valueOf(startTime)), i).toString("yyyy-MM-dd");

          if ("101".equals(type)){
              amount = analysisByDayMapper.findByRecordDate(startTimeStr).getNumRegistered();
          }else if ("102".equals(type)){
              amount = analysisByDayMapper.findByRecordDate(startTimeStr).getNumActive();
          }else {
              amount = analysisByDayMapper.findByRecordDate(startTimeStr).getNumRetention1d();
          }

          //将日期截取出来
          String title = startTimeStr.split("-")[2];

          //封装到users
          Users users = new Users();
          users.setTitle(title);
          users.setAmount(amount);

          thisYears.add(users);
          i++;
      }
        //末期每次循环日期减一
       /* for (int i = 1; !StrUtil.equals(startTimeStr, endTimeStr); i++) {
            startTimeStr = DateUtil.offsetDay(new Date(Long.valueOf(startTime)), i).toString("yyyy-MM-dd");
            //数量
            Integer numRegistered = analysisByDayMapper.findByRecordDate(startTimeStr).getNumRegistered();
            //title 截取出来
            String title = startTimeStr.split("-")[2];

            //新建一个users
            Users users = new Users();
            users.setAmount(numRegistered);
            users.setTitle(title);
            thisYears.add(users);
        }*/

      endTimeStr = DateUtil.offsetDay(new Date(Long.valueOf(endTime)), -365).toString("yyyy-MM-dd");
     // startTimeStr = DateUtil.offsetDay(new Date(Long.valueOf(startTime)), -365).toString("yyyy-MM-dd");
      int j = 0;
      while (!StrUtil.equals(startTimeStr, endTimeStr)){

          //日期往下减
          startTimeStr = DateUtil.offsetDay(new Date(Long.valueOf(startTime)), -(365-j)).toString("yyyy-MM-dd");

          //数量
          Integer numRegistered = analysisByDayMapper.findByRecordDate(startTimeStr).getNumRegistered();

          //title 截取出来
          String title = startTimeStr.split("-")[2];

          //新建一个users
          Users users = new Users();
          users.setAmount(numRegistered);
          users.setTitle(title);
          lastYears.add(users);

          j++;
      }

        UsersVo vo = new UsersVo();
        vo.setThisYear(thisYears);
        vo.setLastYear(lastYears);


        return vo;
    }
}
